<?php namespace App\Http\Controllers\Api;

use App\Example;
use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\Facilitator;
use App\Org;
use App\Services\ImageManager;
use App\User;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Input;
use Response;

class ExampleController extends ApiController
{
    public function setExampleInfo(Guard $guard,$id=0){
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $user = $guard->user();

        if ($id != 0 && Example::whereId($id)->exists())
            $exampleInfo = Example::find($id);
        else
            $exampleInfo = new Example();

        $title = Input::get('title');
        $desc  = Input::get('desc');
        $url   = Input::get('url');
        $exampleId = Input::get('exam_id');
        $orgId = Input::get('org_id');
        $state  = Input::get('state');

        $exampleInfo->org_id = !is_null($orgId) ? $orgId : $exampleInfo->org_id;
        $exampleInfo->title  = !is_null($title) ? $title : $exampleInfo->title;
        $exampleInfo->org_desc = !is_null($desc) ? $desc : $exampleInfo->org_desc;
        $exampleInfo->url    = !is_null($url) ? $url : $exampleInfo->url;
        $exampleInfo->img_exam_id = !is_null($exampleId) ? $exampleId : $exampleInfo->img_exam_id;
        if(!is_null($state))$exampleInfo -> state                = $state;

        $exampleInfo->save();

        return $this->buildResponse(trans('api.exam_setinfo.success'),$exampleInfo);
    }

    public function getExampleInfo(Guard $guard){
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $id = Input::get('id');
        $exampleInfo = Example::find($id);

        return $this->buildResponse(trans('api.get.examinfo.success'),$exampleInfo);
    }

    public function getExamImgByUserId($examId)
    {
        $examInfo = Example::whereId($examId)->first();
        if(!$examInfo)
            return Response::download('images/userlogo.jpg','userlogo.jpg',[],'inline');

        if(!$examInfo->img_exam_id)
            return Response::download('images/userlogo.jpg','userlogo.jpg',[],'inline');

        $photo = $examInfo->examImg;

        if(!$photo || $photo == null)
            return Response::download('images/userlogo.jpg','userlogo.jpg',[],'inline');

        $photoFile = $photo->files;

        if(!$photoFile || $photoFile == null)
            return Response::download('images/userlogo.jpg','userlogo.jpg',[],'inline');

        return Response::download($photoFile->getLocalPath(),$photoFile->file_name,[],'inline');
    }

    public function delExampleById(Guard $guard){
        $id = Input::get('id');

        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        Example::find($id)->delete();

        return $this->buildResponse(trans('api.del_project_team.success'));
    }
}